package com.ctv.my.customview.MaiCustomView.CanvasDraw.utils;

import android.graphics.Point;

import com.ctv.my.customview.MaiCustomView.CanvasDraw.entity.Param;

/**
 * Created by ms on 2017/8/4.
 */

public class IntersectionUtil {
    /**
     * 计算两点组成的直线方程的参数a,b,c
     *
     * @param p1
     * @param p2
     * @return
     */
    public static Param CalParam(Point p1, Point p2) {
        double a, b, c;
        double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y;
        a = y2 - y1;
        b = x1 - x2;
        c = (x2 - x1) * y1 - (y2 - y1) * x1;
        if (b < 0) {
            a *= -1;
            b *= -1;
            c *= -1;
        } else if (b == 0 && a < 0) {
            a *= -1;
            c *= -1;
        }
        return new Param(a, b, c);
    }


    /**
     * 计算两条直线的交点
     *
     * @param pm1
     * @param pm2
     * @return
     */
    public static Point getIntersectPoint(Param pm1, Param pm2) {
        return getIntersectPoint(pm1.a, pm1.b, pm1.c, pm2.a, pm2.b, pm2.c);
    }

    public static Point getIntersectPoint(double a1, double b1, double c1, double a2, double b2, double c2) {
        double m = a1 * b2 - a2 * b1;
        if (m == 0) {
            return null;
        }
        int x = (int) ((c2 * b1 - c1 * b2) / m);
        int y = (int) ((c1 * a2 - c2 * a1) / m);
        return new Point(x, y);
    }
}
